package com.mxjsxz.jigsawcaptcha.demo.controller;

import com.mxjsxz.jigsawcaptcha.constant.CaptchaConstant;
import com.mxjsxz.jigsawcaptcha.demo.model.ReturnResult;
import com.mxjsxz.jigsawcaptcha.enums.CaptchaEnum;
import com.mxjsxz.jigsawcaptcha.model.dto.CaptchaDTO;
import com.mxjsxz.jigsawcaptcha.model.form.CaptchaCheckForm;
import com.mxjsxz.jigsawcaptcha.model.vo.CaptchaVO;
import com.mxjsxz.jigsawcaptcha.utils.CaptchaUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 拼图验证码
 *
 * @author xdl
 * @since 2019-9-5
 */
@RestController
@RequestMapping("jigsaw/captcha")
public class JigsawCaptchaController {
    
    private static final Logger log = LoggerFactory.getLogger(JigsawCaptchaController.class);
    
    @Value("${jigsaw.captcha.path}")
    private String captchaPath;
    
    /**
     * 注册验证码
     *
     * @param request
     * @return 验证码图片信息
     */
    @GetMapping("register")
    public ReturnResult<CaptchaVO> register(HttpServletRequest request) {
        ReturnResult<CaptchaVO> returnResult = new ReturnResult<>();
        if (captchaPath == null) {
            returnResult.setCode(CaptchaEnum.JIGSAW_CAPTCHA_ERROR.code());
            returnResult.setMsg(CaptchaEnum.JIGSAW_CAPTCHA_ERROR.msg());
            return returnResult;
        }
        
        CaptchaDTO captchaDTO = new CaptchaUtil().createCaptcha(captchaPath);
        if (captchaDTO == null) {
            returnResult.setCode(CaptchaEnum.JIGSAW_CAPTCHA_ERROR.code());
            returnResult.setMsg(CaptchaEnum.JIGSAW_CAPTCHA_ERROR.msg());
            return returnResult;
        }
        
        // 生成注册token
        String token = captchaDTO.getToken();
        // session中保存token和x坐标
        HttpSession session = request.getSession();
        session.setAttribute(CaptchaConstant.TOKEN, token);
        session.setAttribute(CaptchaConstant.X, captchaDTO.getX());
        
        returnResult.setCode(0);
        returnResult.setMsg("success");
        returnResult.setData(new CaptchaVO(captchaDTO.getSliceImg(), captchaDTO.getBgImg(), token, captchaDTO.getY()));
        return returnResult;
    }
    
    /**
     * 拼图校验与登录
     *
     * @param request
     * @param form    拼图校验与登录信息
     * @return
     */
    @PostMapping("check")
    public ReturnResult check(HttpServletRequest request, @RequestBody CaptchaCheckForm form) {
        ReturnResult returnResult = new ReturnResult();
        if (StringUtils.isBlank(form.getUsername())) {
            returnResult.setCode(1000000);
            returnResult.setMsg("请填写登录名");
            return returnResult;
        }
        if (StringUtils.isBlank(form.getPassword())) {
            returnResult.setCode(1000001);
            returnResult.setMsg("请填写登录密码");
            return returnResult;
        }
        if (StringUtils.isBlank(form.getToken())) {
            returnResult.setCode(1000002);
            returnResult.setMsg("无效的验证码，请刷新页面");
            return returnResult;
        }
        if (null == form.getSliceX()) {
            returnResult.setCode(CaptchaEnum.JIGSAW_CAPTCHA_SLIDE_FAILED.code());
            returnResult.setMsg(CaptchaEnum.JIGSAW_CAPTCHA_SLIDE_FAILED.msg());
            return returnResult;
        }
        
        // 从session中拿验证数据
        HttpSession session = request.getSession();
        String registerToken = (String) session.getAttribute(CaptchaConstant.TOKEN);
        Integer registerX = (Integer) session.getAttribute(CaptchaConstant.X);
        
        // 验证注册token
        if (!registerToken.equals(form.getToken())) {
            returnResult.setCode(CaptchaEnum.JIGSAW_CAPTCHA_TOKEN_INVALID.code());
            returnResult.setMsg(CaptchaEnum.JIGSAW_CAPTCHA_TOKEN_INVALID.msg());
            return returnResult;
        }
        
        // 验证滑动x坐标
        int diff = registerX - form.getSliceX();
        if (diff < -CaptchaConstant.SLICE_DIFF_LIMIT || diff > CaptchaConstant.SLICE_DIFF_LIMIT) {
            returnResult.setCode(CaptchaEnum.JIGSAW_CAPTCHA_SLIDE_FAILED.code());
            returnResult.setMsg(CaptchaEnum.JIGSAW_CAPTCHA_SLIDE_FAILED.msg());
            return returnResult;
        }
        
        // 登录
        return this.login(request, form.getUsername(), form.getPassword());
    }
    
    /**
     * 登录
     *
     * @param request
     * @param username 用户登录名
     * @param password 密码
     * @return 登录结果
     */
    private ReturnResult login(HttpServletRequest request, String username, String password) {
        // TODO 登录校验
        log.info("username:{}", username);
        log.info("password:{}", password);
        
        ReturnResult returnResult = new ReturnResult();
        returnResult.setCode(0);
        returnResult.setMsg("登录成功");
        return returnResult;
    }
    
}
